<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
        <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
        <title>AUI快速完成布局</title>
        <link rel="stylesheet" type="text/css" href="../../css/aui.2.0.css" />
        <style type="text/css">
            body {
                background: #ffffff;
            }
            .aui-bar {
                margin-top: 0rem;
            }
            #demo .aui-bar-btn-item.aui-active {
                background-color: transparent;
                color: #212121;
            }
        </style>
    </head>
    <body>
        <header class="aui-bar aui-bar-nav" style="">
            <div class="aui-bar aui-bar-btn aui-bar-btn-round">
                <div class="aui-bar-btn-item aui-active" style="width: 5rem !important">
                    密码登录
                </div>
                <div class="aui-bar-btn-item"  style="width: 5rem !important">
                    验证码登录
                </div>
            </div>
        </header>
        <section id="passwordLogin" class="aui-content" style="display: block">
            <div class="aui-content aui-margin-b-15">
                <ul class="aui-list aui-form-list">
                    <li class="aui-list-header"></li>
                    <li class="aui-list-item">
                        <div class="aui-list-item-inner">
                            <div class="aui-list-item-label-icon">
                                <i class="aui-iconfont aui-icon-mobile"></i>
                            </div>
                            <div class="aui-list-item-input">
                                <input id="pwPhoneText" type="tel" placeholder="请输入手机号">
                            </div>
                        </div>
                    </li>
                    <li class="aui-list-item">
                        <div class="aui-list-item-inner">
                            <div class="aui-list-item-label-icon">
                                <i class="aui-iconfont aui-icon-lock"></i>
                            </div>
                            <div class="aui-list-item-input">
                                <input id="passwordText" type="password" placeholder="请输入密码">
                            </div>
                            <div class="aui-list-item-label-icon">
                                <i class="aui-iconfont aui-icon-hide"></i>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
            <div style="padding: 1rem 1rem 1rem 1rem;">
                <div id="loginToServer" class="aui-btn aui-btn-info aui-btn-block" tapmode onclick="pwLoginToServer()">
                    点击登录
                </div>
                <div style="display:-webkit-flex;display:flex;-webkit-justify-content:space-between; justify-content:space-between;">
                    <div style="color: #039be5; padding-top: 1rem" onclick="resetPassword()">
                        忘记密码?
                    </div>
                    <div style="color: #039be5; padding-top: 1rem" onclick="userRegister()">
                        注册
                    </div>
                </div>
            </div>
        </section>
        <section id="verifyCodeLogin" class="aui-content" style="display: none">
            <div class="aui-content aui-margin-b-15">
                <ul class="aui-list aui-form-list">
                    <li class="aui-list-header"></li>
                    <li class="aui-list-item">
                        <div class="aui-list-item-inner">
                            <div class="aui-list-item-label-icon">
                                <i class="aui-iconfont aui-icon-mobile"></i>
                            </div>
                            <div class="aui-list-item-input">
                                <input id="vcPhoneText" type="tel" placeholder="请输入手机号">
                            </div>
                        </div>
                    </li>
                    <li class="aui-list-item">
                        <div class="aui-list-item-inner">
                            <div class="aui-list-item-label-icon" style="width: auto">
                                <i class="aui-iconfont aui-icon-lock"></i>
                            </div>
                            <div class="aui-list-item-input" style="width: 55%">
                                <input id="verifyCodeText" type="text" placeholder="请输入验证码">
                            </div>
                            <div id="verifyCodeBtn" class="aui-btn aui-btn-info aui-btn-block aui-btn-sm" tapmod onclick="getVerifyCode()" style="margin: 0.1rem 0.3rem 0.1rem 0.3rem; width: 35%">
                                获取验证码
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
            <div style="padding: 1rem 1rem 1rem 1rem;">
                <div id="loginToServer" class="aui-btn aui-btn-info aui-btn-block" tapmode onclick="vcLoginToServer()">
                    点击登录
                </div>
                <div style="display:-webkit-flex;display:flex;-webkit-justify-content:space-between; justify-content:space-between;">
                    <div style="color: #039be5; padding-top: 1rem"></div>
                    <div style="color: #039be5; padding-top: 1rem" onclick="userRegister()">
                        注册
                    </div>
                </div>
            </div>
        </section>
    </body>
    <script type="text/javascript" src="../../script/api.js" ></script>
    <script type="text/javascript" src="../../script/aui-tab.js" ></script>
    <script type="text/javascript" src="../../script/aui-toast.js" ></script>
    <script type="text/javascript" src="../../script/aui-dialog.js" ></script>
    <script>
        var toast = new auiToast();
        var dialog = new auiDialog();
        var model = null;
        var user = null;
        function countDownVerifyCode() {
            var verifyCodeBtn = document.getElementById("verifyCodeBtn");
            verifyCodeBtn.textContent = "60秒后重新获取";
            verifyCodeBtn.removeAttribute('onclick');
            var id = setInterval(countDown, 1000);
            var count = 60;
            function countDown() {
                if (count == 0) {
                    clearInterval(id);
                    verifyCodeBtn.textContent = "获取验证码";
                    verifyCodeBtn.setAttribute('onclick', 'getVerifyCode()');
                } else {
                    count--;
                    verifyCodeBtn.textContent = count + "秒后重新获取";
                    verifyCodeBtn.removeAttribute('onclick');
                }
            }

        }

        apiready = function() {
            api.setRefreshHeaderInfo({
                visible : true,
                bgColor : '#ccc',
                textColor : '#fff',
                textDown : '下拉刷新...',
                textUp : '松开刷新...',
                showTime : true
            }, function(ret, err) {
                api.refreshHeaderLoadDone();
            });
            model = api.require('model');
            model.config({
                appId : 'A6928874653494',
                appKey : '4B6C428C-24C2-F9E7-3175-F983922E8C8F',
                host : 'https://d.apicloud.com'
            });
            user = api.require('user');
            api.parseTapmode();
        }
        var bar = document.querySelectorAll(".aui-bar-btn-round");
        if (bar) {
            for (var i = 0; i < bar.length; i++) {
                var d = bar[i];
                var tab = new auiTab({
                    element : bar[i],
                    repeatClick : true
                }, function(ret) {
                    //alert(ret.index);
                    var passwordLogin = document.getElementById("passwordLogin");
                    var verifyCodeLogin = document.getElementById("verifyCodeLogin");
                    if (ret.index == 1) {
                        passwordLogin.style.display = "block";
                        verifyCodeLogin.style.display = "none";
                    } else {
                        passwordLogin.style.display = "none";
                        verifyCodeLogin.style.display = "block";
                    }
                });
            }
        }
        function getVerifyCode() {
            var phone = document.getElementById('vcPhoneText').value;
            var vcPhoneText = parseInt(phone);
            if (isNaN(vcPhoneText) || vcPhoneText > 99999999999 || vcPhoneText < 10000000000) {
                toast.fail({
                    title : "号码错误！",
                    duration : 1000
                });
                return;
            }
            countDownVerifyCode();
            toast.loading({
                title : "请稍候",
                duration : 2000
            }, function(ret) {
                console.log(ret);
                setTimeout(function() {
                    toast.hide();
                }, 30000)
            });
            var smsVerify = api.require('smsVerify');
            smsVerify.register(function(ret, err) {
                if (ret.status) {
                    //api.alert({msg: '注册成功'});
                    smsVerify.sms({
                        phone : phone,
                        country : "86"
                    }, function(ret, err) {
                        if (ret.status) {
                            if (ret.smart == true) {// 安卓版特有功能 智能验证
                                var query = api.require('query');
                                var queryId = 0;
                                var userId = "";
                                query.createQuery(function(ret, err) {
                                    if (ret) {
                                        queryId = ret.qid;
                                        if (queryId) {
                                            query.limit({
                                                qid : queryId,
                                                value : 1
                                            });
                                            query.whereEqual({
                                                qid : queryId,
                                                column : 'username',
                                                value : phone
                                            });
                                            model.findAll({
                                                class : "user",
                                                qid : queryId
                                            }, function(ret, err) {
                                                if (ret) {
                                                    //alert(JSON.stringify(ret));
                                                    toast.hide();
                                                    toast.success({
                                                        title : "本机之前已通过验证！自动登录成功！",
                                                        duration : 2000
                                                    });
                                                    user.login({
                                                        username : ret[0].username,
                                                        password : ret[0].passwordBackup,
                                                    }, function(ret2, err) {
                                                        finishLogin(ret[0].id, ret[0].username, ret[0].passwordBackup);
                                                    });
                                                    //setTimeout(function() {
                                                    //    finishLogin(ret[0].id, ret[0].username, ret[0].passwordBackup);
                                                    //}, 1000);
                                                } else {
                                                    alert("本机之前已通过验证！直接登录失败！ " + JSON.stringify(err));
                                                }
                                            });
                                        }
                                    } else {
                                        alert("本机之前已通过验证！直接登录失败！ " + JSON.stringify(err));
                                    }
                                });
                            } else {
                                toast.hide();
                                toast.success({
                                    title : "短信发送成功！",
                                    duration : 1000
                                });
                            }
                        } else {
                            api.alert({
                                msg : err.code + ' ' + err.msg
                            });
                        }
                    });
                } else {
                    api.alert({
                        msg : err.code + ' 注册失败'
                    });
                }
            });
        }

        function finishLogin(id, username, password) {
            //alert('id: ' + id);
            $api.setStorage('userID', id);
            $api.setStorage('username', username);
            $api.setStorage('password', password);
            var sqlCmd = "INSERT INTO UserInfo VALUES ('" + id + "', '" + username + "', '" + password + "', 1)";
            //alert(sqlCmd);
            var db = api.require('db');
            db.executeSql({
                name : 'loanMarketDB',
                sql : sqlCmd
            }, function(ret, err) {
                if (ret.status) {
                    //alert(JSON.stringify(ret));
                    toast.hide();
                    toast.success({
                        title : "登录成功",
                        duration : 1000
                    });
                    api.sendEvent({
                        name : 'ev_finishLogin',
                        extra : {
                            phone : username,
                        }
                    });
                    api.sendEvent({
                        name : 'ev_loanBtn_login',
                        extra : {
                            phone : username,
                        }
                    });
                    api.sendEvent({
                        name : 'ev_frm4_login',
                        extra : {
                            phone : username,
                        }
                    });
                    api.sendEvent({
                        name : 'ev_forum_login',
                    });
                } else {
                    alert(JSON.stringify(err));
                }
            });
        }

        function vcLoginToServer() {
            var phoneText = document.getElementById('vcPhoneText').value;
            var vcPhoneText = parseInt(phoneText);
            var verifyCodeText = document.getElementById("verifyCodeText").value;
            if (isNaN(vcPhoneText) || vcPhoneText > 99999999999 || vcPhoneText < 10000000000) {
                dialog.alert({
                    title : "手机号码错误！",
                    msg : '请重新输入^_^',
                    buttons : ['确定']
                });
                return;
            }
            toast.loading({
                title : "验证中",
                duration : 2000
            }, function(ret) {
                console.log(ret);
                setTimeout(function() {
                    toast.hide();
                }, 30000)
            });
            var smsVerify = api.require('smsVerify');
            smsVerify.register(function(ret, err) {
                if (ret.status) {
                    //api.alert({msg: '注册成功'});
                    smsVerify.verify({
                        phone : phoneText,
                        country : "86",
                        code : verifyCodeText
                    }, function(ret, err) {
                        if (ret.status) {
                            var query = api.require('query');
                            var queryId = 0;
                            var userId = "";
                            query.createQuery(function(ret, err) {
                                if (ret) {
                                    queryId = ret.qid;
                                    if (queryId) {
                                        query.limit({
                                            qid : queryId,
                                            value : 1
                                        });
                                        query.whereEqual({
                                            qid : queryId,
                                            column : 'username',
                                            value : phoneText
                                        });
                                        model.findAll({
                                            class : "user",
                                            qid : queryId
                                        }, function(ret, err) {
                                            if (ret) {
                                                //alert(JSON.stringify(ret));
                                                user.login({
                                                    username : ret[0].username,
                                                    password : ret[0].passwordBackup,
                                                }, function(ret2, err) {
                                                    finishLogin(ret[0].id, ret[0].username, ret[0].passwordBackup);
                                                });
                                            } else {
                                                alert("验证成功，登录失败！ " + JSON.stringify(err));
                                            }
                                        });
                                    }
                                } else {
                                    alert("验证成功，登录失败！ " + JSON.stringify(err));
                                }
                            });
                        } else {
                            toast.hide();
                            toast.fail({
                                title : "验证失败！",
                                duration : 1000
                            });
                        }
                    });
                } else {
                    api.alert({
                        msg : err.code + ' 注册失败'
                    });
                }
            });
        }

        function pwLoginToServer() {
            var phoneText = document.getElementById("pwPhoneText").value;
            var pwPhoneText = parseInt(document.getElementById("pwPhoneText").value);
            var passwordText = document.getElementById("passwordText").value;
            if (isNaN(pwPhoneText) || pwPhoneText > 100000000000 || pwPhoneText < 1) {
                dialog.alert({
                    title : "手机号码错误！",
                    msg : '请重新输入^_^',
                    buttons : ['确定']
                });
                return;
            }
            toast.loading({
                title : "登录中",
                duration : 2000
            }, function(ret) {
                console.log(ret);
                setTimeout(function() {
                    toast.hide();
                }, 30000)
            });
            user.login({
                username : pwPhoneText,
                password : passwordText,
            }, function(ret, err) {
                if (ret) {
                    if (ret.error) {
                        toast.hide();
                        //alert(JSON.stringify(ret));
                        var errMsg = "";
                        if (ret.error.status == 401) {
                            errMsg = "用户名密码错误！"
                        } else {
                            errMsg = ret.error.message;
                        }
                        dialog.alert({
                            title : "登录失败，错误原因：",
                            msg : errMsg,
                            buttons : ['确定']
                        });
                    } else {
                        //alert(JSON.stringify(ret));
                        finishLogin(ret.userId, phoneText, passwordText);
                    }
                } else {
                    //alert(JSON.stringify(err));
                    toast.hide();
                    var errMsg = "";
                    if (err.status == 401) {
                        errMsg = "用户名密码错误！"
                    } else {
                        errMsg = err.message;
                    }
                    dialog.alert({
                        title : "登录失败！错误原因：",
                        msg : errMsg,
                        buttons : ['确定']
                    });
                }
            });
        }

        function userRegister() {
            var delay = 0;
            if (api.systemType != 'ios') {
                delay = 300;
            }
            api.openWin({
                name : 'user_register_win',
                url : './user_register_win.html',
                bounces : false,
                delay : delay,
                slidBackEnabled : true,
                vScrollBarEnabled : false,
                animation : {
                    type : "movein", //动画类型（详见动画类型常量）
                    subType : "from_left", //动画子类型（详见动画子类型常量）
                    duration : delay //动画过渡时间，默认300毫秒
                }
            });
        }

        function resetPassword() {
            var delay = 0;
            if (api.systemType != 'ios') {
                delay = 300;
            }
            api.openWin({
                name : 'reset_password_win',
                url : './reset_password_win.html',
                bounces : false,
                delay : delay,
                slidBackEnabled : true,
                vScrollBarEnabled : false,
                animation : {
                    type : "movein", //动画类型（详见动画类型常量）
                    subType : "from_left", //动画子类型（详见动画子类型常量）
                    duration : delay //动画过渡时间，默认300毫秒
                }
            });
        }
    </script>
</html>